# -- coding: utf-8 --
# @Time : 2023/1/5 9:57
# @Author : RLH
# @File : yaml_utils_module.py
# 功能描述: 操作yaml文件

# 系统第三方库  
import os
import yaml
import io
# 导入项目模块





class YamlUtilsClass:


    def read_yaml_func(self, yaml_path, *kwargs):
        '''
        读取yaml文件，支持不传关键字，或传入多级关键字
        :param yaml_path: yaml文件路径
        :param kwargs: 支持不传关键字，或传入多级关键字 '一级关键字','二级关键字' ···
        :return: yaml文件数据，不传关键字就返回整个文件内容，传入关键字就返回关键字的内容
        '''
        with io.open(yaml_path, mode='r', encoding='utf-8') as file:
        # with open(yaml_path, mode='r') as file:
            file_data = yaml.load(stream=file, Loader=yaml.FullLoader)
            # file_data = yaml.safe_load(file)
        return file_data



    def write_yaml_func(self, yaml_path, data):
        '''
        # 写入yaml文件
        :param yaml_path:  yaml 文件路径
        :param data:  写入的数据
        :return:  无返回
        '''
        with io.open(yaml_path, mode='w', encoding='utf-8') as f:
            yaml.dump(data=data, stream=f, allow_unicode=True)

    # def write_w_yaml_func(self, yaml_path, data):
    #     '''
    #     # 覆盖的形式写入yaml文件
    #     :param yaml_path:  yaml 文件路径
    #     :param data:  写入的数据
    #     :return:  无返回
    #     '''
    #     with io.open(yaml_path, mode='w', encoding='utf-8') as f:
    #         yaml.dump(data=data, stream=f, allow_unicode=True)

    def clear_yaml_func(self, yaml_path):
        '''
        清空yaml文件
        :param yaml_path:  yaml 文件路径
        :return:  无返回
        '''
        with io.open(yaml_path, mode='w', encoding='utf-8') as f:
            f.truncate()

    def yaml_data_dict(self, yaml_file_path):
        '''将文件目录下的所以yaml文件读出来，放进字典中进行返回'''
        conf_yaml_data = {}
        # 加载所有YAML文件
        for filename in os.listdir(yaml_file_path):
            if filename.endswith('.yml') or filename.endswith('.yaml'):
                # 通过YamlUtilsCls.read_yaml_func读取YAML文件中的数据
                # os.path.join(yaml_file_path, filename) 函数将目录和文件拼接到一起
                file_data = self.read_yaml_func(os.path.join(yaml_file_path, filename))
                # 通过update(file_data)函数，将字典数据加载到一起
                conf_yaml_data.update(file_data)
        return conf_yaml_data

YamlUtilsCls = YamlUtilsClass()

